import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

import routes from './routes'
import homeConfig from './homeConfig'
import { loadUserMenus } from '../api/index'

import { useBaseStore } from '../stores/useBaseStore'
let baseStore = null

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

router.beforeEach(async (to, from, next) => {
  // 初始化仓库
  if (baseStore == null) {
    baseStore = useBaseStore()
  }
  console.log(to.path)
  // 判断是否为公开路由
  if (to.meta.isPublic) {
    next()
    return
  }
  // 判断非公开页面访问是否已经登录
  if (baseStore.token == '') {
    next('/login')
    ElMessage.error({
      message: '请先登录',
    })
    return
  }
  // 判断登录用户是否具有权限访问需要跳转的页面
  // 方式1：判断拦截：都需要获取当前用户存在那些权限
  // 方式2：动态路由生成：都需要获取当前用户存在那些权限
  //                   用户权限列表查询只能在守卫中完成
  if (baseStore.menus.length == 0) {
    let data = await loadUserMenus()
    baseStore.menus = data
    // console.log(baseStore.menus);
    // console.log(router)
    // 循环并获取当前用户的home子路由信息
    for (let m of baseStore.menus) {
      let path = m.right_path
      let name = path.replace(/^\/home/, '').replace(/\//g, '')
      // console.log(router.hasRoute(name))
      if (!router.hasRoute(name)) {
        // 不存在该路由
        let component = homeConfig[path]
        // console.log(path, component)
        // 将获取的路由信息，和组件地址，增加到当前路由表中
        router.addRoute('home', {
          path,
          name,
          component,
        })
      }
      // console.log(router)
    }
  }
  next()
})

export default router
